package com.learn.sunday.stock.common;

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.listener.Event;
import com.alibaba.nacos.api.naming.listener.EventListener;
import com.alibaba.nacos.client.naming.NacosNamingService;
import com.learn.sunday.stock.configure.NacosConfigure;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.Properties;
import java.util.concurrent.Executor;

@Slf4j
@Component
public class NacosConfigUtils {

    @Autowired
    private NacosConfigure NacosConfigure;


    @Bean
    public ConfigService getConfig(NacosConfigure nacosConfigure) throws NacosException {
        Properties properties = new Properties();
        //设置Nacos节点对应的IP地址
        properties.setProperty("serverAddr",nacosConfigure.getServerAddr());
        //设置命名空间
        //properties.setProperty("namespace",nacosConfigure.getNamespace());
        //如果开启了Nacos权限校验，设置用户名
        properties.setProperty("username",nacosConfigure.getUsername());
        properties.setProperty("password",nacosConfigure.getPassword());
        //设置获取配置信息的轮询超时时间
        //properties.setProperty(PropertyKeyConst.CONFIG_LONG_POLL_TIMEOUT,"3000");

        //设置获取配置信息失败后的重试次数
        //properties.setProperty(PropertyKeyConst.CONFIG_RETRY_TIME,"5");

        //设置是否开启客户端主动拉取最新的配置信息
        //properties.setProperty(propertyKeyConst.MAX_RETRY,"5");
        //构造一个ConfigService实例
        //订阅配置
        ConfigService configService = NacosFactory.createConfigService(properties);
        log.info("构造实例成功!");
        configService.addListener("ext-config-common01.properties", "sunday", new Listener() {
            @Override
            public Executor getExecutor() {
                return null;
            }

            @Override
            public void receiveConfigInfo(String configInfo) {
                log.info("接收到消息变更:{}",configInfo);
            }
        });

        //订阅服务
        NacosNamingService nacosNamingService = new NacosNamingService(nacosConfigure.getServerAddr());

        nacosNamingService.subscribe("service-stock", new EventListener() {
            @Override
            public void onEvent(Event event) {
                log.info("---- {}" , JSON.toJSONString(event));
            }
        });

        return configService;
    }
}
